<template>
	<div>
		<CustomDialog
			:title="state.dialog.title"
			v-model:visible="state.dialog.isShowDialog"
			dialogWidth="1100px"
			@close="closeDialog"
			:dialogFooterBtn="true"
		>
			<!-- <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog"> -->
			<div>
				<splitpanes class="default-theme" @resize="paneSize = $event[0].size">
					<pane :size="20">
						<div>
							<el-tree
								style="max-width: 600px"
								:data="fileSearchState.fileCatalogData"
								node-key="id"
								:props="defaultProps"
								:expand-on-click-node="false"
								default-expand-all
								@node-click="handleChoiceFileCatalog"
							/>
						</div>
					</pane>
					<pane :size="80">
						<el-card shadow="hover" class="layout-padding-auto">
							<div class="system-file-search mb15">
								<el-form ref="fileSearchDialogFormRef" size="default" :model="fileSearchState" label-width="100px" class="table-form">
									<el-row>
										<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
											<el-form-item label="文件名称" prop="originalName">
												<el-input size="default" placeholder="请输入文件名称" clearable style="width: 100%" v-model="fileSearchState.originalName">
												</el-input>
											</el-form-item>
										</el-col>

										<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
											<el-form-item label="创建时间" prop="searchDateTime">
												<el-date-picker
													type="datetimerange"
													v-model="fileSearchState.searchDateTime"
													start-placeholder="创建开始时间"
													end-placeholder="创建时间"
													style="width: 100%"
												/>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mt10">
											<el-form-item class="table-form-btn" label-width="10px">
												<el-button size="default" type="primary" class="ml10" @click="handleSearch">
													<el-icon>
														<ele-Search />
													</el-icon>
													查询
												</el-button>
											</el-form-item>
										</el-col>
									</el-row>
								</el-form>
							</div>
							<el-row :gutter="5" id="content">
								<el-col v-for="file in state.tableData.data" :xs="24" :sm="12" :md="6" :lg="4" :xl="4" :key="file.id">
									<el-card class="file-content" :class="{ active: selected(file.id) }">
										<div class="item">
											<el-image
												v-if="file.fileType == 'image'"
												:src="file.visitAbsPath"
												fit="contain"
												class="image"
												:preview-src-list="[file.visitAbsPath]"
											/>
											<el-image
												v-else
												:src="file.coverImagePath"
												fit="contain"
												class="image"
												@click.stop="onOpenAndDownloadFile(file.fileType, file.originalName, file.visitAbsPath)"
											/>
										</div>
										<div class="bottom-content">
											<el-tooltip class="box-item" effect="dark" content="选中多张文件" placement="top-start">
												<div @click="onHandleFileSelect(file)">
													<el-icon v-if="selected(file.id)" color="var(--el-color-primary)"><SuccessFilled /> </el-icon>
													<el-icon v-else>
														<CircleCheck />
													</el-icon>
												</div>
											</el-tooltip>
										</div>
										<div class="bottom-choice">
											<el-tooltip class="box-item" effect="dark" content="选中单张文件" placement="top-start">
												<el-button @click.stop="onChoiceFile(file)" size="default">选择 </el-button>
											</el-tooltip>
										</div>
									</el-card>
								</el-col>
							</el-row>
							<el-pagination
								class="mt15"
								:pager-count="15"
								:page-sizes="[10, 15, 20, 30, 50, 100]"
								v-model:current-page="state.tableData.paging.currentPage"
								background
								v-model:page-size="state.tableData.paging.pageSize"
								layout="total, sizes, prev, pager, next, jumper"
								:total="state.tableData.paging.totalCount"
							>
							</el-pagination>
						</el-card>
					</pane>
				</splitpanes>
			</div>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="closeDialog" size="default">取 消</el-button>
					<el-button type="primary" @click="batchChoiceFile" size="default">确 认</el-button>
				</div>
			</template>
			<!-- </el-dialog> -->
		</CustomDialog>
		<VideoDialog ref="VideoDialogRef"></VideoDialog>

		<AudioDialog ref="AudioDialogRef"></AudioDialog>
	</div>
</template>

<script setup lang="ts">
import { fileApi } from '/@/api/file/index';

import { reactive, ref, defineAsyncComponent, onMounted, nextTick, watch } from 'vue';
import { CircleCheck, SuccessFilled } from '@element-plus/icons-vue';
import msg from '/@/utils/messageUtils';
import _ from 'lodash';
const VideoDialog = defineAsyncComponent(() => import('/@/views/file/videoDialog.vue'));

const AudioDialog = defineAsyncComponent(() => import('/@/views/file/audioDialog.vue'));

import 'splitpanes/dist/splitpanes.css';

import { Splitpanes, Pane } from 'splitpanes';

const paneSize = ref(50);
const VideoDialogRef = ref();
const AudioDialogRef = ref();

const emit = defineEmits(['choiceFile']);

const prop = defineProps<CallbackProp>();

let choiceFiles: ChoiceFileInfo[] = [];

const defaultProps = {
	children: 'children',
	label: 'catalogName',
};

interface CallbackProp {
	param?: string;
	fileType?: string;
}

const FileCatalogProps = {
	checkStrictly: true,
	value: 'id',
	label: 'catalogName',
	emitPath: false,
};

const fileSearchState = reactive({
	originalName: '',
	startSearchDateTime: null,
	endSearchDateTime: null,
	searchDateTime: [],
	fileCatalogId: '',
	fileCatalogData: [],
});

const state = reactive({
	dialog: {
		title: '选择图片',
		isShowDialog: false,
	},
	isToggle: false,
	tableData: {
		data: [],
		total: 0,
		loading: false,
		paging: {
			currentPage: 1,
			pageSize: 15,
			totalCount: null,
			totalPages: null,
		},
	},
});

const selectedFileIds = ref<Set<string>>(new Set());

const handleChoiceFileCatalog = (data: any) => {
	console.log('data: ', data);
	fileSearchState.fileCatalogId = data.id;
	handleSearch();
};

const loadFileCatalog = async () => {
	try {
		const { data } = await fileApi().tree_catalog();
		console.log('fileCatalog: ', data);
		fileSearchState.fileCatalogData = data;
	} catch (error) {
		msg().error('获取文件分类失败');
	}
};

const onChoiceFile = (obj: any) => {
	const choiceFileInfo: ChoiceFileInfo = {
		id: obj.id,
		originalName: obj.originalName,
		coverImagePath: obj.coverImagePath,
		visitAbsPath: obj.visitAbsPath,
		visitRelativePath: obj.visitRelativePath,
	};
	emit('choiceFile', [choiceFileInfo], prop);
	closeDialog();
};

const batchChoiceFile = () => {
	console.log('批量选择.....');
	emit('choiceFile', choiceFiles, prop);
	closeDialog();
};

const closeDialog = () => {
	state.dialog.isShowDialog = false;
	choiceFiles = [];
	selectedFileIds.value.clear();
};

const loadFileChoiceTableData = async () => {
	try {
		const { data } = await fileApi().search({
			catalogId: fileSearchState.fileCatalogId,
			startSearchDateTime: fileSearchState.startSearchDateTime,
			endSearchDateTime: fileSearchState.endSearchDateTime,
			originalName: fileSearchState.originalName,
			offset: (state.tableData.paging.currentPage - 1) * state.tableData.paging.pageSize,
			limit: state.tableData.paging.pageSize,
		});
		state.tableData.data = data.datas;
		state.tableData.paging.currentPage = data.paging.currentPage;
		state.tableData.paging.totalCount = data.paging.totalCount;
		console.log('data: ', data);
	} catch (error) {
		msg().error('获取文件列表失败');
	}
};

const openFileChoiceDialog = () => {
	state.dialog.isShowDialog = true;
	loadFileCatalog();
	loadFileChoiceTableData();
};

const onHandleSizeChange = (val: number) => {
	state.tableData.paging.pageSize = val;
	state.tableData.paging.currentPage = 1;
	loadFileChoiceTableData();
};

const onHandleFileSelect = (file: string) => {
	if (selectedFileIds.value.has(file.id)) {
		let index = _.findIndex(choiceFiles, (e) => e.id === file.id);
		choiceFiles.splice(index, 1);
		selectedFileIds.value.delete(file.id);
	} else {
		const choiceFileInfo: ChoiceFileInfo = {
			id: file.id,
			originalName: file.originalName,
			coverImagePath: file.coverImagePath,
			visitAbsPath: file.visitAbsPath,
			visitRelativePath: file.visitRelativePath,
		};
		choiceFiles.push(choiceFileInfo);
		selectedFileIds.value.add(file.id);
	}
};
const selected = (id: any) => {
	// return true;
	return selectedFileIds.value.has(id);
};

watch(
	() => state.tableData.paging.currentPage,
	(newV, oldv) => {
		console.log(`currentPage, newV: ${newV}, oldV : ${oldv}`);
		onHandleCurrentChange(newV);
	}
);

watch(
	() => state.tableData.paging.pageSize,
	(newV, oldv) => {
		console.log(`pageSize, newV: ${newV}, oldV : ${oldv}`);
		onHandleSizeChange(newV);
	}
);

const onOpenAndDownloadFile = (type: string, name: string, url: string) => {
	if (type == 'video') {
		VideoDialogRef.value.openVideoDialog(name, url);
	} else if (type == 'audio') {
		AudioDialogRef.value.openAudioDialog(name, url);
	} else {
		window.open(url);
	}
};

const handleSearch = () => {
	const st: any = fileSearchState.searchDateTime;
	if (st.length > 0) {
		fileSearchState.startSearchDateTime = st[0].getTime();
		fileSearchState.endSearchDateTime = st[1].getTime();
	}
	loadFileChoiceTableData();
};

const onHandleCurrentChange = (val: number) => {
	loadFileChoiceTableData();
};

const cal_span = () => {
	console.log('number: ');
	return 3;
};

defineExpose({
	openFileChoiceDialog,
});
</script>

<style scoped lang="scss">
.image {
	width: 100%;
	display: block;
	height: 120px;
	cursor: pointer;
}

.main {
	display: flex;
	flex-wrap: wrap;
	justify-content: flex-start;
}

.item {
	// width: 100px;
	// height: 100px;
	padding-top: 5px;
	flex: 1;
	box-sizing: border-box;
	display: flex;
	justify-content: center;
	align-items: center;
}

.file-content {
	position: relative;
	cursor: pointer;
	margin-bottom: 10px;
	box-sizing: border-box;
	:deep(.el-card__body) {
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: auto;
		padding: 0px;
		.el-table {
			flex: 1;
		}
	}
}

.bottom-content {
	//width: 100%;
	overflow: hidden;
	cursor: pointer;
	white-space: nowrap;
	text-overflow: ellipsis;
	height: 40px;
	display: flex;
	align-items: center;
	font-size: 20px;
	&:hover {
		background-color: var(--next-bg-color);
	}
	padding-left: 10px;
}

.active {
	//border: 2px solid #2980b9;
	//box-sizing: border-box;
}

.bottom-choice {
	padding: 5px;
	width: 100%;
	text-align: right;
}
</style>
